package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    @RequestMapping("/submit")
    public Result submitOrder(@RequestBody Map map){
        //需要先判断当前验证码输入的是否正确
        String code = (String) map.get("validateCode");
        //获取手机号
        String telephone = (String) map.get("telephone");
        //获取redis存储的验证码
        String codeRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        if(code==null){
            return new Result(false,"请输入验证码");
        }
        if(codeRedis==null){
            return new Result(false,"验证码已经失效，请重新获取");
        }
        if(code!=null && codeRedis!=null && code.equals(codeRedis)){
            //如果验证码匹配正确 删除redis中存储的验证码
            jedisPool.getResource().del(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        }else{
            return new Result(false,"验证码输入错误，请核对！");
        }
        //应该先把方式出入map中 是微信预约还是电话预约
        map.put("orderType", Order.ORDERTYPE_WEIXIN);

        Result result= null;
        try {
            //调用预约方法
            result = orderService.order(map);
        } catch (Exception e) {
            //预约失败
            e.printStackTrace();
            return result;
        }
        /*if(result.isFlag()){
            //预约成功
            //预约成功，可以为用户发送短信
            try{
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone, (String) map.get("orderDate"));
            }catch (Exception e){
                e.printStackTrace();
            }
        }*/
        return result;
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Map map  = orderService.findById4Detail(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }

}
